import { useState, useEffect, useContext } from "react";
import { NavBar, List, InfiniteScroll, IndexBar } from "antd-mobile";
import { useHistory } from 'react-router-dom';
import pinyin from 'pinyin';

import AvatarImage from "../../../components/AvatarImage";
import { MySdkStoreContext } from '../../../context';

import "./style.scss";

export default function() {
  const charCodeOfA = 'A'.charCodeAt(0);
  const groupsKey = {};
  Array(27)
    .fill('')
    .map((_, i) => {
      groupsKey[i === 26 ? '#' : String.fromCharCode(charCodeOfA + i)] = [];
    })

  const mapToArray = (map) => {
    return Object.keys(map)
      .filter(key => map[key]?.length)
      .map((title) => ({
        title,
        items: map[title]
      }));
  };

  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const [pagination, setPagination] = useState({ pageIndex: 1, totalItmeCount: 0 });
  const [group, setGroup] = useState(mapToArray(groupsKey));

  const getMailList = (pageIndex: number) => {
    // todo: 接口返回的排序方式不支持使用indexBar组件
    mySdkStore.sdk.queryFriend({ pageIndex, pageSize: 150 }).then(({ next, rows, totalItmeCount }) => {
      setPagination({ pageIndex: +next, totalItmeCount });
      rows.forEach((item) => {
        const name = item.userName || item.nickName;
        const letters = pinyin(name, { style: pinyin.STYLE_FIRST_LETTER });
        const code = (letters[0]?.[0]?.[0] || '').toUpperCase();
        if (groupsKey[code]) {
          groupsKey[code].push(item);
        } else {
          groupsKey['#'].push(item);
        }
      });
      setGroup(mapToArray(groupsKey));
    });
  }

  const getNextData = async () => {
    await getMailList(pagination.pageIndex + 1);
  }

  useEffect(() => {
    getMailList(1);
  }, []);

  return (<div className="groupMemberPage" style={{ height: window.innerHeight }}>
      <NavBar onBack={() => history.goBack()} style={{ background: '#fff', border: 'none' }}>我的好友</NavBar>
      <IndexBar>
        {group.map(g => {
          const { title, items } = g;
          return (
            <IndexBar.Panel
              index={title}
              title={title}
              key={`${title}`}
            >
            <List header={title} style={{ '--border-top': 0, '--border-bottom': 0, '--border-inner': 0 }}>
              {items.map(item => {
                return <List.Item
                    key={item.userId}
                    prefix={<AvatarImage
                    src={item.avatarUrl}
                    style={{ borderRadius: 8 }}
                    fit='cover'
                    width={42}
                    height={42}
                    nickName={item.nickName}
                    userName={item.userName}
                    userId={item.userId}
                  />}
                  description={<>ID: {item.userId}</>}
                >
                  <a onClick={() => history.push({ pathname: `/userInfo/${item.userId}` })}>{item.userName}</a>
                </List.Item>
              })}
            </List>
          </IndexBar.Panel>
          )
        })}
        <InfiniteScroll loadMore={getNextData} hasMore={false} />
      </IndexBar>
  </div>
  )
}